package com.fafu.forum.controller;

import com.fafu.forum.common.AppResult;
import com.fafu.forum.common.ResultCode;
import com.fafu.forum.config.AppConfig;
import com.fafu.forum.model.Message;
import com.fafu.forum.model.User;
import com.fafu.forum.services.IMessageService;
import com.fafu.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Slf4j
@Api(tags = "站内信接口")
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IUserService userService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send (HttpServletRequest request,
                           @ApiParam("收信id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                           @ApiParam("内容") @RequestParam("content") @NonNull String content){
        // 1. 登录用户当前的状态, 是否为禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 2. 不能给自己发站内信
        if (user.getId() == receiveUserId) {
            return AppResult.failed("不能给自己发送站内信");
        }
        // 3. 校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1) {
            return AppResult.failed("接收者状态异常");
        }
        // 4. 封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        // 5. 调用 service 层
        messageService.create(message);
        // 6. 返回结果
        return AppResult.success("发送信息成功");
    }

    @ApiOperation("获取未读数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount (HttpServletRequest request) {
        // 1. 获取当前的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调用 service 方法
        Integer count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);
    }

    /**
     * 查询用户的所有站内信
     * @return 站内信集合
     */
    @ApiOperation("查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll (HttpServletRequest request) {
        // 1. 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 2. 调用 service 层
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        // 3. 返回结果
        return AppResult.success(messages);
    }

    @ApiOperation("更新为已读")
    @PostMapping("/markRead")
    public AppResult markRead (HttpServletRequest request,
                               @ApiParam("站内信Id") @RequestParam("id") @NonNull Long id) {
        // 1. 根据 id 查询站内信
        Message message = messageService.selectById(id);
        // 2. 站内信是否存在
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 3. 站内信是不是自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getId() != message.getReceiveUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用 service 层
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    /**
     * 回复消息
     * @param repliedId 要回复的站内信Id
     * @param content 要回复的站内信Id
     * @return AppResult
     */
    @ApiOperation("回复消息")
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                               @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                               @ApiParam("内容") @RequestParam("content") @NonNull String content) {
        // 1. 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 校验要恢复的站内信
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            // 返回错误秒速
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给自己回复
        if (user.getId() == existsMessage.getPostUserId()) {
            // 返回错误描述
            return AppResult.failed("不能回复自己的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);
        // 调用 service 层
        messageService.reply(repliedId,message);
        return AppResult.success();
    }
}
